<!--  -->
<template>
  <card>
      <div class="block" style="margin-bottom: 20px;">
    <span class="demonstration">录入时间:</span>
    <el-date-picker
      v-model="value1"
      type="datetimerange"
      value-format="yyyy-MM-dd HH:mm:ss"
      range-separator="至"
      start-placeholder="开始日期"
      end-placeholder="结束日期"
      @change="fdataChange(value1)"
      >
    </el-date-picker>
  </div>
    <div style="display: flex; justify-content: space-between;"  direction="vertical">     
     <div>
        <span>姓名: </span><el-input style="width:200px;margin-right: 20px;" v-model="sname" placeholder="请输入姓名"></el-input>
        <span>手机号: </span><el-input style="width:200px;margin-right: 20px;" v-model="sphone" placeholder="请输入手机号"></el-input>
        <span>身份证号: </span> <el-input style="width:200px" v-model="sidNum" placeholder="请输入身份证号"></el-input>
         <el-button type="primary" @click="search">查询</el-button>
         <el-button type="warning" @click="reset">重置</el-button>
      </div>
      <div>
        <el-button type="primary" style="width:150px; height: 40px;" @click="openCount()">
          开启出口计数
          <Tooltip max-width="200" content="开启出口计数"
                placement="bottom">
                <Icon style="margin-left: 5px;" size="16" type="ios-help-circle-outline" />
              </Tooltip>
        </el-button>
      </div>
    </div>
  
    <div style="margin: 20px 0px;" direction="vertical">
      <div>
        <span>人员类型:</span>
        <RadioGroup v-model="status" type="button" @on-change="change(status)">
          <Radio label="0" checked="checked">全部</Radio>
          <Radio label="1">工作人员</Radio>
          <!-- <Radio label="2">参观者</Radio> -->
          <Radio label="3">临时人员</Radio>
        </RadioGroup>
        <Button type="primary" @click="formvisible = true; modalTitle = '新增人员'; edit(1)">新增人员</Button>
        <Button type="primary" @click="delAll()">批量删除</Button>
        <Button type="primary" @click="downAll()">批量重新下放设备</Button>
      </div>
      <Table :columns="columns" :data="tableData" ref="selection" @on-selection-change="handleSelectionChange">
        <template #img="{ row }">
          <img :src="row.faceUrl" alt="" width="100px">
        </template>
        <template #action="{ row, index }">
          <Button type="primary" size="middle" style="margin-right: 5px"
            @click="formvisible = true; modalTitle = '修改信息'; edit(row)">修改</Button>
          <Button type="warning"  size="middle"  @click="show(row)">查看</Button>
          <Button type="error" size="middle" @click="open(row)">删除</Button>
        </template>
      </Table>
      <Modal title="详细信息" v-model="modal1" width="50">
        <!-- <Spin fix size="large" v-if="loading3"></Spin> -->
        <Table class="table" highlight-row :columns="column1" :data="tableData1" style="width: 100% !important;">
        </Table>
        <!--点击查看的时候这个modal1弹出来  -->
        <div slot="footer">
          <Button type="warning" class="Button" @click="formvisible = true">关闭</Button>
        </div>
      </Modal>
      
      <!-- 新增和修改按钮 -->
      <el-dialog :title="modalTitle" :visible.sync="formvisible" append-to-body="false">
        <el-form :model="subjectName" :rules="rules" ref="ruleForm">
          <el-form-item label="人员姓名" prop="name">
            <el-input v-model="subjectName.name" autocomplete="off" :disabled="disabled"></el-input>
          </el-form-item>
          <el-form-item label="证件号码" prop="cardNum">
            <el-input v-model="subjectName.cardNum" autocomplete="off" :disabled="disabled"></el-input>
          </el-form-item>
          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="subjectName.phone" autocomplete="off" :disabled="disabled"></el-input>
          </el-form-item>           
          <el-form-item label="有效时间" prop="ordertime" class="block">
            <!-- <span class="demonstration" style="display: block;"> 有效时间</span> -->
              <el-date-picker    
                v-model="ordertime"
                type="datetimerange"
                :disabled="disabled"
                value-format="yyyy-MM-dd HH:mm:ss"
                start-placeholder="有效开始时间"
                end-placeholder="有效结束时间"
                :default-time="['00:00:00']">
              </el-date-picker>
          </el-form-item>
          <el-form-item label="设备型号" prop="deviceIds" :disabled="disabled" >
            <el-select  v-model="value3" multiple placeholder="请选择" :disabled="disabled">
              <el-option v-for="item in options" :key="item.id" :label="item.deviceName" :value="item.deviceName" :disabled="disabled">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="人脸照片" :disabled="disabled">        
            <vue-uploadimg :imgUrl="imgurl1" url="chongqing/stage/file/uploadFile" @uploadImg="uploadImg1" v-if="showimg">
            </vue-uploadimg>            
            <img :src="subjectName.faceUrl" alt="" width="700px" v-else>
            <!-- <div :class="!subjectName.faceUrl ? 'notext' : '' ">无</div>            -->
          </el-form-item>
          <el-form-item label="人员性别">
            <template>
              <el-radio-group v-model="subjectName.gender"  :disabled="disabled">
                <!-- <el-radio v-model="subjectName.sex" label="1">男</el-radio>
                    <el-radio v-model="subjectName.sex" label="0">女</el-radio> -->
                <el-radio label="male">男</el-radio>
                <el-radio label="female">女</el-radio>
              </el-radio-group>

            </template>
          </el-form-item>
          <el-form-item label="人员类别" >

            <el-radio-group v-model="subjectName.identityType" :disabled="disabled">
              <el-radio label="工作人员">工作人员</el-radio>

              <el-radio label="临时人员">临时人员</el-radio>
            </el-radio-group>

          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="formvisible = false" v-if="showbutton">取 消</el-button>
          <el-button type="primary" @click="submit()" v-if="showbutton">保存并下放设备</el-button>
        </div>
      </el-dialog>
    </div>
    <div class="block">
    <span class="demonstration"></span>
    <el-pagination
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
      :current-page="currentPage"
      :page-size="pageSize"
      :page-sizes="[10, 20, 30, 50]"
      layout="total,sizes, prev, pager, next, jumper"
      :total="total">
      <!-- 少一个sizes不显示每页多少条 -->
    </el-pagination>
  </div>
  </card>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
  function IdentityCodeValid(rule, value, callback) {
  if(!value){
    return true, callback();
  }
  if (
    !value ||
    !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(
      value
    )
  ) {
    callback(new Error('身份证号格式错误'));
  } 
}
// function Ordertime(rule, value, callback){
//   if(!value){
//     callback(new Error('请选择时间'))
//   }
// }

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    //这里存放数据
    return {
      multipleSelection:[],
      status:'0',
      ordertime:'',
      showimg:true,
      sname:'',
      sphone:'',
      baryid:'',
      sidNum:'',
      disabled:false,
      // 按钮数据
      showbutton:true,
      total: 0,
      query: '',
      currentPage:'', // 当前页数
      pageSize: 10, // 当前每页显示多少条数据
      sTime: "",
      eTime: "",
      value:[],
      options: [],
      value3: ['1号设备'],
      type: ["姓名","身份证号","手机号"],
      queryType: [],
      condition: [],
      imgurl1: "",
      modalTitle: "修改人员",
      identityType: "",
      subjectName: {
        name: '',
        cardNum: "",
        phone: "",
        faceUrl: "",
        sex: "",
        // mustAnswer: true,
        // options: null,
        // serialNumber: 0,
        identityType: "",
        //  input1: '',
        // input2: '',
        // input3: ''
        sTime:'',
        eTime:''

      },
      rules: {
        name: [{
          required: true,
          message: '请输入用户姓名',
          trigger: 'blur'
        },
        {
          min: 2,
          max: 15,
          message: '长度在 2 到 10 个字符',
          trigger: 'blur'
        }
        ],
        ordertime:[{
          required: true,
          message: '请选择时间',
          trigger: 'blur'
        },
        // {
        //   validator: Ordertime,
        //   trigger: 'blur',
        //  }
        {
          validator: (rule, value, callback) => {
            if (!validMobile(value)) {
              callback(new Error("请选择时间"));
            }
          },
          message: "请选择时间"
        }
        ],
          deviceIds: [{
          required: true,
          message: '请选择设备型号',
          trigger: 'blur'
        },
        {    
          message: '请至少选择一项设备型号',
          trigger: 'blur'
        }
        ],
        cardNum: [{
          required: true,
          message: '请输入用户身份证号',
          trigger: 'blur'
        },
         {
          validator: IdentityCodeValid,
          trigger: 'blur',
         }
        ],       
        phone: [{ required: true, message: "请输入手机号码", trigger: "blur" },
                { min: 11, max: 11, message: "请输入11位手机号码", trigger: "blur" },
                {
                  pattern: /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/,
                  message: "请输入正确的手机号码"
                },
                {
                  validator: (rule, value, callback) => {
                    if (!validMobile(value)) {
                      callback(new Error("请输入正确的手机号"));
                    }
                  },
                  message: "请输入正确的手机号码"
                }
                ]
              },
      formvisible: false,
      tableData1: [],
      tempData1: [],
      modal1: false,
      value1: [],
      value2: ['2016-01-01', '2016-02-15'],
      cityList: [
        {
          value: 'New York',
          label: 'New York'
        },
        {
          value: 'London',
          label: 'London'
        }
      ],
      model: '',
      radio1: '全部',
      columns: [
        {
          type: "selection",
          width: 60,
          align: "center",
        },
        {
          type: "index",
          title: '编号',
          align: 'center'
        },
        {
          title: '姓名',
          key: 'name'
        },
        {
          title: '人员类型',
          key: 'identityType',
        },
        {
          title: '人脸图片',
          key: 'faceUrl',
          slot: 'img'

        },
        {
          title: '操作',
          width: 260,
          slot: 'action',
          align: "center"
        }
      ],
      column1: [
        {
          type: "selection",
          width: 60,
          align: "center",
        },
        {
          type: "index",
          title: '编号',
          align: 'center'
        },
        {
          title: '姓名',
          key: 'name'
        }, {
          title: '证件号码',
          key: 'cardNum'
        },
        {
          title: '手机号',
          key: 'phone'
        }

      ],
      data: [
        {
          name: 'John Brown',
          age: 18,
          address: 'New York No. 1 Lake Park',
          date: '2016-10-03'
        },
        {
          name: 'Jim Green',
          age: 24,
          address: 'London No. 1 Lake Park',
          date: '2016-10-01'
        }
      ],
      tableData: [],    
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {
    value1(newValue){
      // console.log(newValue);
      if(newValue===null){
        this.getData()
      }
    }
  },
  //方法集合
  methods: {
    openCount(){
      this.$http(
        "/chongqing/stage/face/openExitCount",
        {

        },
        "get",
        (res)=>{
          console.log(res,"开启计数");
        }
      )

    },
    handleSelectionChange(val){
      this.multipleSelection=val
      console.log(this.multipleSelection);
    },
    delAll(){
      if(this.multipleSelection.length<=0){
        this.$confirm("请选择人员进行删除")
      }else{
        var arr=[]
      this.multipleSelection.forEach(row=>arr.push(row.id))
      this.$confirm('确定全部删除吗', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'success',
        callback: action => {
          if (action === 'confirm') {
            //批量删除
            this.$http(
              "/chongqing/stage/face/batchDelete",
              {
                "ids":arr
              },
              "post",
              (res)=>{
                console.log(res);
                this.$notify({
                title: '删除成功',
                message: '',
                type: 'success',
                duration: 2000
              })
              this.getData()  //重新加载页面的方法
              }
            )
          }
        }
      })

      }
      
    
    },
    downAll(){
      if(this.multipleSelection.length<=0){
        this.$confirm("请选择人员进行下放设备")
      }else{
        var arr=[]
      this.multipleSelection.forEach(row=>arr.push(row.id))
      this.$confirm('确定全部下放设备吗', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'success',
        callback: action => {
          if (action === 'confirm') {
            //批量删除
            this.$http(
              "/chongqing/stage/face/batchBindStaff",
              {
                "ids":arr
              },
              "post",
              (res)=>{
                console.log(res);
                this.$notify({
                title: '下放成功',
                message: '',
                type: 'success',
                duration: 2000
              })
              this.getData()  //重新加载页面的方法
              }
            )
          }
        }
      })
      }
    },
   
     search(){
        console.log(this.sname);
        console.log(this.sphone);
        console.log(this.sidNum);
      this.getData()
      },
      reset(){
          this.sname=''
          this.sphone=''
          this.sidNum=''
          this.getData()
      },
      handleSizeChange(pageSize) {
        // console.log(`每页 ${val} 条`);
        this.pageSize = pageSize;
        this.currentPage=1;
        this.getData();
      },
      handleCurrentChange(currentPage) {
        console.log(`当前页: ${currentPage}`);
          this.currentPage = currentPage;
          this.getData();
      },
    fdataChange(value1){
      console.log(value1);
       
       if(value1 == null){
        this.sTime = ''
        this.sTime = ''
       }else{
        this.sTime = value1[0]
        this.sTime = value1[1]
       }
       console.log( this.sTime );
       console.log( this.eTime );
      this.getData()
    },
  
    // 临时人员筛选
    change(state) {
     this.tableData = this.tempData1
      let arr = this.tableData    
      console.log(arr);
      if (state == 0) {
        this.identityType= ""
        this.getData()
        console.log();
      } else if (state == 1) {
        this.$http(
        "/chongqing/stage/face/findStaffInfoPage",  
        {
          // current:0,
          endDate: "",
          identityType: "工作人员",
          name: "",
          orders: [
            {
              asc: true,
              column: ""
            }
          ],
          startDate:"",
          size: 10,
          current: 1,
          gender:''          
        },
        "post",
        (res) => {
          console.log("工作人员res", res);
          this.tableData = res.data.data.records
          this.tempData1 = res.data.data.records
          this.identityType= "工作人员"
          console.log("页面数据res", this.tableData);
          this.total=this.tableData.length          
        }
      )        
      } else {
        // this.tableData = arr.filter(function (value, index) {
        //   return value.identityType === "临时人员"
        // })
        //   _this.getData()
          this.$http(
        "/chongqing/stage/face/findStaffInfoPage",  
        {
          // current:0,
          endDate: "",
          identityType: "临时人员",
          name: "",
          orders: [
            {
              asc: true,
              column: ""
            }
          ],
          startDate:"",
          size: 10,
          current: 1,
          gender:''          
        },
        "post",
        (res) => {
          console.log("临时人员res", res);
          this.tableData = res.data.data.records
          this.tempData1 = res.data.data.records
          this.identityType= "临时人员"
          console.log("页面数据res", this.tableData);
          this.total=this.tableData.length          
        }
      ) 
      }  
    },
    //请求设备
    getList() {
      this.$http(
        "/chongqing/stage/face/findDeviceSelectors",
        {},
        "post",
        (res) => {
          console.log(res, '我是下发设备');
          this.options = res.data.data
        }
      )
    },
    //获取身份类型
    httptypeList() {
      this.$http(
        "/chongqing/stage/face/findIdentityTypeSelector",
        {},
        "post",
        (res) => {
          console.log(res, "我是身份类型");
        }
      )
    },
    // 页面数据
    async getData() {
      await this.$http(
        "/chongqing/stage/face/findStaffInfoPage",  
        {
          cardNum: this.sidNum,
          // current: 1,
          name: this.sname,
          phone: this.sphone,
          startDate:this.sTime,
          endDate:this.eTime,
          identityType:this.identityType,
         
          orders: [
            {
              asc: true,
              column: ""
            }
          ],
          
          size: this.pageSize,
          current: this.currentPage,
          gender:''
          
        },
        "post",
        (res) => {
          console.log("页面数据res", res);
          this.tableData = res.data.data.records
          this.tempData1 = res.data.data.records
          console.log("页面数据res0000", this.tableData);
          this.total=res.data.data.total          
        }
      )

    },
    //查看的按钮
    show(row) {
      const ArraiIds = []
        this.options.map((item)=>{
          console.log(item);
          this.tableData[row._index].deviceIds.split(",").map((items)=>{
            console.log(items);
            if(item.id === items){
              // console.log("qwertyuio");
              ArraiIds.push(item.deviceName)
            }
          })
          console.log(ArraiIds,"5555555555555555555555555888888888888888888888888888");
        })
      this.showimg=false,
        this.disabled=true,
        this.ordertime = [row.startTime,row.endTime]
        this.modalTitle = '查看详情'
        this.value3 = ArraiIds
        // this.value3 = []
        this.formvisible = true
        this.showbutton = false      
        this.subjectName = {
          // endDate:row.endTime,
          // startDate:row.startTime,
          name: row.name,
          cardNum: row.cardNum,
          phone: row.phone,
          faceUrl: row.faceUrl,
          gender: row.gender,
          id:Number(row.id),
          identityType: row.identityType,
        }
        // this.value3.push(this.tableData[row._index].deviceIds)
        this.imgurl1 = row.faceUrl
        this.formvisible = true
  },
    // 新增和修改按钮
    edit(row) {
      if (row == 1) {
        this.ordertime = ''//有效时间为空
        this.showimg=true,
        this.disabled=false,
        this.showbutton = true
        this.value3 = []
        this.formvisible = true
        this.subjectName = {
          name: '',
          cardNum: "",
          phone: "",
          faceUrl: "",
          gender: "",
          identityType: "",
          endDate:"",
          startDate:"",

        }
        this.imgurl1 = ''
      }
       else {
        console.log(this.options,"");
        console.log(this.tableData[row._index].deviceIds.split(","),"");
        const ArraiIds = []
        this.options.map((item)=>{
          console.log(item);
          this.tableData[row._index].deviceIds.split(",").map((items)=>{
            console.log(items);
            if(item.id === items){
              // console.log("qwertyuio");
              ArraiIds.push(item.deviceName)
            }
          })
          console.log(ArraiIds,"5555555555555555555555555888888888888888888888888888");
        })
        this.showimg=true,
        this.disabled=false,
        this.showbutton = true
        this.value3 =   ArraiIds
        console.log(row);
        console.log(this.ordertime);
        this.ordertime = [row.startTime,row.endTime]
        console.log(this.eTime);
        this.subjectName = {
          // endTime:row.endTime,
          // startTime:row.startTime,
          name: row.name,
          cardNum: row.cardNum,
          phone: row.phone,
          faceUrl: row.faceUrl,
          gender: row.gender,
          id:Number(row.id),
          identityType: row.identityType,
        }     
        // this.value3.push(this.tableData[row._index].deviceIds)
        this.imgurl1 = row.faceUrl
        this.formvisible = true
      }


    },
    // 上传图片
    uploadImg1(data) {
      console.log(data, "我是上传图片")
      // this.newData2.pic = data
      this.imgurl1 = data
      console.log(this.imgurl1)
    },
    //   删除
    del(row) {
      this.$http("/chongqing/stage/face/deleteStaffById", {
        id: Number(row.id)
      }, "get", (res) => {
        console.log(res);
        if (res.data.code == 1000) {
          this.getData()
        }
      })
    },
    //   删除的弹窗
    open(row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.del(row)
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 点击提交按钮
    submit() {
      // var _this = this
     const arrayid =[]
      this.value3.map((item)=>{
        this.options.map((items)=>{
          if(item === items.deviceName){
            console.log(items.id);
            arrayid.push(items.id)
          }
        })
      })

      console.log(this.value3 ,"");
      if (this.modalTitle == "新增人员") {
        this.$http('/chongqing/stage/face/saveOrUpdateStaff',
          {
            cardNum: this.subjectName.cardNum,
            deviceIds: arrayid.toString(),
            endTime: this.ordertime[1],
            faceUrl: this.imgurl1,
            id: 0,
            identityType: this.subjectName.identityType,
            name: this.subjectName.name,
            phone: this.subjectName.phone,
            startTime: this.ordertime[0],
            gender:this.subjectName.gender,
            // deviceName:this.value3
          },
          'post',
          (res) => {  
            console.log("新增res", res);
            if (res.data.code == 1000 && res.data.data) {
              this.$Message.success('新增成功')
              this.formvisible = false
              this.getData()
            }else {
              this.errorMessage(res.data.msg)
            }
          },
        )
      }
      else{
        console.log("我是修改",this.value3[0]);
        console.log(this.eTime, this.sTime,"woshi99999999999999999999");
        console.log(this.subjectName);
        this.$http('/chongqing/stage/face/saveOrUpdateStaff',
          {
            cardNum: this.subjectName.cardNum,
            deviceIds: arrayid.toString(),
            endTime: this.ordertime[1],
            faceUrl: this.imgurl1,
            id: this.subjectName.id,//用户id
            identityType: this.subjectName.identityType,
            name: this.subjectName.name,
            phone: this.subjectName.phone,
            startTime: this.ordertime[0],
            gender: this.subjectName.gender,
            // deviceName:this.value3           
          },
          'post',
          (res) => {
            console.log("修改res", res);
            if (res.data.code == 1000 && res.data.data) {
              this.formvisible = false
              this.getData()
              this.$Message.success('修改成功')
            } else {
              this.errorMessage(res.data.msg)
            }
          }
        )
      }
      this.eTime = '';
      this.sTime = '';
    },

  },
  beforeCreate() { }, //生命周期 - 创建之前
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    console.log(this.Dtime);
  },
  beforeMount() { }, //生命周期 - 挂载之前
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.getData()
    this.getList()
    this.httptypeList()
  },
  beforeUpdate() { }, //生命周期 - 更新之前
  updated() { }, //生命周期 - 更新之后
  beforeDestroy() { }, //生命周期 - 销毁之前
  destroyed() { }, //生命周期 - 销毁完成
  activated() { }, //如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style>
.notext{
  display: none;
}
</style>